#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <unistd.h>

#define MSG_KEY 1234
#define MSG_SIZE 256

int main() {
    int msgid;
    struct msgbuf msg, reply;
    pid_t pid = getpid();

    // 获取消息队列
    msgid = msgget(MSG_KEY, 0666);
    if (msgid == -1) {
        perror("msgget (client)");
        exit(EXIT_FAILURE);
    }
    printf("Client %d: Connected to message queue with ID %d\n", pid, msgid);

    // 发送消息
    msg.mtype = 1;  // 发送类型固定为1
    snprintf(msg.mtext, MSG_SIZE, "hello from Process %d", pid);
    if (msgsnd(msgid, &msg, strlen(msg.mtext) + 1, 0) == -1) {
        perror("msgsnd (client)");
        exit(EXIT_FAILURE);
    }
    printf("Client %d: Sent message: %s\n", pid, msg.mtext);

    // 等待服务器回执
    if (msgrcv(msgid, &reply, sizeof(reply.mtext), pid, 0) == -1) {
        perror("msgrcv (client)");
        exit(EXIT_FAILURE);
    }
    printf("Client %d: Received reply: %s\n", pid, reply.mtext);

    return 0;
}